<template>
  <div class="login-cmpt__uploader-wrapper">
    <div class="login-cmpt__uploader" :class="{
      'uploaded': !!v
    }" @click="onClick">
      <input ref="uploader" class="uploader__input" hidden type="file" />
      <img class="uploader-img" :src="v" alt="" v-if="v" />
      <template v-else>
        <img class="add-icon" src="src/assets/img/add.png" />
        <p class="uploader__title">{{ title || 'upload' }}</p>
      </template>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, onMounted } from 'vue'

export default defineComponent({
  props: {
    value: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    }
  },
  setup(props, ctx) {
    const v = computed<string>({
      get() {
        return props.value
      },
      set(v) {
        ctx.emit('update:value', v);
      }
    });


    return {
      v
    }
  },
  mounted() {
    const uploader = this.$refs.uploader as HTMLInputElement;
    uploader.addEventListener('change', (event) => {
      if (uploader.files?.[0]) {
        this.upload(uploader.files[0])
      }
    }, false);
  },
  methods: {
    onClick() {
      if (this.v) {
        return;
      }
      const uploader = this.$refs.uploader as HTMLInputElement;
      uploader.value = '';
      uploader.click();
    },
    upload(file: File) {
      const reader = new FileReader();
      reader.onload = (e) => {
        console.log(e)
        if (e.target?.result) {
          this.v = e.target.result as string;
          console.log(this.v)
        }
      }


      reader.readAsDataURL(file);
    }
  }
})
</script>


<style lang="stylus">
@import '../../../styles/mixin.styl';

.login-cmpt__uploader-wrapper
  display inline-block
  vertical-align middle
  margin .12rem
.login-cmpt__uploader
  Flex(column, center, center)
  text-align center
  width 1.2rem
  height 1.2rem
  background #f5f5f5
  border 1px dashed #C1C7D0 
  color #AAA
  &.uploaded
    background #fff
  .uploader__title
    margin 0
  .uploader-img
    max-width 100%
    max-height 100%
  .add-icon
    width .64rem
    height @width

    
</style>